import Vue from "vue";
import axios from "axios";
import {
  getCookie, removeCookie
} from "@/utils";
import errorCode from './errorCode'
import store from "@/store";

const request = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL+'/api',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
//  请求拦截器
// request interceptor
request.interceptors.request.use(config => {
  const token = getCookie('YIQIU_TOKEN')
  console.log('token', token)
  if (token) {
    config.headers.Accept = `application/json`
    // config.headers.Authorization = token
    config.headers.token = token
  }
  return config
})
// 响应拦截
request.interceptors.response.use((res) => {
  // 未设置状态码则默认成功状态
  const code = JSON.parse(res.data).code;
  console.log('JSON.parse',code)
  const msg = errorCode[code] || res.msg || errorCode['default']
  // 二进制数据则直接返回
  if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
    return JSON.parse(res.data)
  }
  if (msg == '该token已过期' || msg == '该token未认证' || msg == '非法token') {
    removeCookie("YIQIU_TOKEN");
    // store.dispatch('Login', idValue);
  }
  else if (code === 500) {
    message.error(msg)
    return Promise.reject(new Error(msg))
  } else if (code === 601) {
    message.error(msg)
    return Promise.reject(new Error(msg))
  } else if (code != 0) {
    console.log('err11' + msg)
    message.error(msg)
    return Promise.resolve(JSON.parse(res.data))
    // return Promise.reject('error')
  } else {
    return Promise.resolve(JSON.parse(res.data))
  }
},
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    message.error(msg)
    return Promise.reject(error)
  })

Vue.prototype.$http = request;
export { request };
